<template>
  <BasicModal v-bind="$attrs" @register="registerModal" title="权限配置" @ok="handleSubmit">
    <div class="tree-wrapper">
      <a-tree
        v-if="treeData.length"
        ref="treeRef"
        checkable
        checkStrictly
        defaultExpandAll
        :selectable="false"
        :treeData="treeData"
        :checkedKeys="checkedKeys"
        @check="handleCheck"
      />
    </div>
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, unref, toRaw, nextTick } from 'vue';
  import { Tree } from 'ant-design-vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { getMenus } from '/@/router/menus';
  import { getPermissionTree, savePermissionTree } from '/@/api/system/system';
  import { getMenuTreePermission } from '/@/utils/helper/menuPermissionHelper';
  import { useMessage } from '/@/hooks/web/useMessage';

  export default defineComponent({
    name: 'MenuPermissionModal',
    components: { BasicModal, [Tree.name]: Tree },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      let id = '';
      let type = '';
      const treeData = ref([]);
      const checkedKeys = ref([]);
      const treeRef = ref(null);

      const { createMessage } = useMessage();

      /**
       * 获取权限树数据
       */
      const getMenusData = async (id, type) => {
        const menus = await getMenus();
        const permissionData = await getPermissionTree({ id: id, type: type });
        const menuTreeData = getMenuTreePermission(permissionData.tree, [], menus);
        treeData.value = menuTreeData;
        checkedKeys.value = permissionData.value;
        nextTick(() => {
          setModalProps({ confirmLoading: false, loading: false });
        });
      };

      const [registerModal, { setModalProps, closeModal }] = useModalInner((data) => {
        id = data.id;
        type = data.type;
        setModalProps({ confirmLoading: true, maskClosable: false, loading: true });
        getMenusData(id, type);
      });

      /******************节点checkbox点击事件处理S*******************/
      function handleCheck(checkedKeys2, e) {
        const checked = checkedKeys2.checked;
        let data: any = Object.assign([], treeData.value);
        const pos = e.node.pos.split('-');
        if (e.checked) {
          // 选中当前节点的所有父节点和所有的子节点
          let i = 1;
          for (i = 1; i < pos.length - 1; i++) {
            if (!checked.includes(data[pos[i]].key)) {
              checked.push(data[pos[i]].key);
            }
            data = data[pos[i]].children;
          }
          data = data[pos[i]].children;
          if (data) {
            checkedAllChildrenKey(checked, data);
          }
        } else {
          for (let i = 1; i < pos.length; i++) {
            data = data[pos[i]].children;
          }
          unCheckedAllChildrenKey(checked, data);
        }
        checkedKeys.value = checkedKeys2;
      }

      function checkedAllChildrenKey(checked, children) {
        if (children) {
          for (let i = 0; i < children.length; i++) {
            if (!checked.includes(children[i].key)) {
              checked.push(children[i].key);
            }
            checkedAllChildrenKey(checked, children[i].children);
          }
        }
      }

      function unCheckedAllChildrenKey(checked, children) {
        if (children) {
          for (let i = 0; i < children.length; i++) {
            if (checked.includes(children[i].key)) {
              var index = checked.indexOf(children[i].key);
              if (index > -1) {
                checked.splice(index, 1);
              }
            }
            unCheckedAllChildrenKey(checked, children[i].children);
          }
        }
      }
      /******************节点checkbox点击事件处理E*******************/

      async function handleSubmit() {
        try {
          setModalProps({ confirmLoading: true });
          let data = [];
          const checkedKeysData: any = toRaw(unref(checkedKeys));
          const checked = checkedKeysData.checked;
          if (checked) {
            data = checked.join();
          } else {
            data = checkedKeysData.join();
          }
          await savePermissionTree({ id: id, type: type, data: data });
          createMessage.success('保存成功');
          closeModal();
          emit('success');
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { treeRef, registerModal, handleSubmit, treeData, checkedKeys, handleCheck };
    },
  });
</script>

<style lang="less" scoped>
  .tree-wrapper {
    // min-height: 400px;
    // margin-top: 5px;

    ::v-deep(.tree_float) {
      float: left;
    }

    ::v-deep(.tree_clear) {
      clear: both;
    }

    ::v-deep(.ant-tree-child-tree > li) {
      padding-top: 8px;
    }

    // ::v-deep(.vben-basic-tree-title) {
    //   display: block;
    //   margin-left: -0.5rem;
    // }

    // ::v-deep(.ant-tree-checkbox-inner) {
    //   // margin-left: 8px;
    // }

    // ::v-deep(.ant-tree li .ant-tree-node-content-wrapper.ant-tree-node-selected) {
    //   background-color: null;
    // }
  }
</style>
